package com.seafwg.designmode;

/**
 * @Author seafwg
 * @Date 2022/7/24 00:13
 * @Version 1.0
 * @description 单例模式
 */

public class Singleton {
    public static void main(String[] args) {
        SingletonHunger singletonHunger = SingletonHunger.getInstance();
        SingletonHunger singletonHunger1 = SingletonHunger.getInstance();

        if (singletonHunger == singletonHunger1) {
            System.out.println("YES");
        }
        System.out.println("OK");

        SingletonLazy instance = SingletonLazy.getInstance();
        SingletonLazy instance1 = SingletonLazy.getInstance();

        if (instance.equals(instance1)) {
            System.out.println("YES");
        }
    }
}

/**
 * 饿汉模式
 */
class SingletonHunger{
    /**
     * 静态属性生成实例
     */
    private static SingletonHunger instance = new SingletonHunger();

    public SingletonHunger() {}

    /**
     * 供一个静态方法获取实例
     * @return 当前类的实例
     */
    public static SingletonHunger getInstance() {
        return instance;
    }
}

/**
 * 懒汉模式
 */
class SingletonLazy{
    /**
     * 声明静态属性，不会创建对象
     */
    private static SingletonLazy instance;

    public SingletonLazy() {}

    /**
     * 判断实例对象是否存在，根据存在与否创建对象
     * @return
     */
    public static SingletonLazy getInstance() {
        if(instance == null) {
            //有现成安全问题
            instance = new SingletonLazy();
        }
        return instance;
    }

}